"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 防篡改
Case Name   : INDENDPENDT用户对自己表的表级备份
Create At   : 2022/3/29
Owner       : @daiguatutu
Description :
    1.设置参数并重启数据库enableseparationofduty=off
    2.创建independent和sysadmin用户
    3.切换independent用户,创建表并插入数据
    4.超级用户将pg_catalog.pg_roles的权限赋给independent用户
    5.independent用户执行gs_dump backup语句
    6.超级用户删除表
    7.independent用户执行gs_dump restore语句
    8.切换independent用户,查询表
    9.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.成功
    6.成功
    7.成功
    8.成功
    9.清理环境成功
History     :
    Modified by @daiguatutu 2023/02/07: 修改teardown，删除dump输出文件
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class Security(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_node = Node('PrimaryDbUser')
        self.pri_root = Node('PrimaryRoot')
        self.constant = Constant()
        self.common = Common()
        self.u_name = 'u_security_indenpendentuser_0034'
        self.u_name_01 = 'u_security_indenpendentuser_0034_01'
        self.t_name = 't_security_indenpendentuser_0034'
        self.default_value1 = self.common.show_param('enableSeparationOfDuty')
        self.dump_path = os.path.join(macro.DB_INSTANCE_PATH,
                                      f'{self.t_name}.sql')

    def test_security(self):
        text = '-----step1：设置参数并重启数据库enableSeparationOfDuty=off; ' \
               'expect:成功-----'
        self.log.info(text)
        if self.default_value1 != 'off':
            mod_msg = self.pri_sh.execute_gsguc('set',
                                                self.constant.GSGUC_SUCCESS_MSG,
                                                'enableSeparationOfDuty=off')
            self.assertTrue(mod_msg, '执行失败:' + text)
            result = self.pri_sh.restart_db_cluster()
            self.assertTrue(result, '执行失败' + text)

        text = '-----step2：创建independent和sysadmin用户 expect:成功-----'
        self.log.info(text)
        create_cmd = f"drop user if exists {self.u_name}," \
            f"{self.u_name_01} cascade; " \
            f"create user {self.u_name} independent password " \
            f"'{macro.COMMON_PASSWD}';" \
            f"create user {self.u_name_01} sysadmin " \
            f"password '{macro.COMMON_PASSWD}';"
        msg = self.pri_sh.execut_db_sql(create_cmd)
        self.log.info(msg)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, msg,
                      '执行失败:' + text)
        self.assertEqual(2, msg.count(self.constant.CREATE_ROLE_SUCCESS_MSG),
                         '执行失败:' + text)

        text = '-----step3：切换independent角色,创建表并插入数据; expect:成功-----'
        self.log.info(text)
        sql_cmd = f"create table {self.t_name}(id int,address text);" \
            f"insert into {self.t_name} values (1,'beijing'),(2,'shanxi');"
        connect = f'-U {self.u_name} -W {macro.COMMON_PASSWD}'
        msg = self.pri_sh.execut_db_sql(sql_cmd, sql_type=connect)
        self.log.info(msg)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, msg, '执行失败:' + text)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, msg, '执行失败:' + text)

        text = '-----step4：超级用户将pg_catalog.pg_roles的权限赋给independent用户; ' \
               'expect:成功-----'
        self.log.info(text)
        sql_cmd = f"grant all privileges on pg_catalog.pg_roles " \
            f"to {self.u_name};"
        msg = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(msg)
        self.assertIn(self.constant.GRANT_SUCCESS_MSG, msg, '执行失败:' + text)

        text = '-----step5：independent用户执行gs_dump backup语句; expect:成功-----'
        self.log.info(text)
        dump_cmd = f'source {macro.DB_ENV_PATH};' \
            f'gs_dump -U  {self.u_name} -W {macro.COMMON_PASSWD} ' \
            f'-p {self.pri_node.db_port}  {self.pri_node.db_name} ' \
            f'-f {self.dump_path} ' \
            f'-t {self.u_name}.{self.t_name} -F t --no-subscriptions'
        msg = self.common.get_sh_result(self.pri_node, dump_cmd)
        self.assertIn(f'dump database {self.pri_node.db_name} successfully',
                      msg, '执行失败:' + text)

        text = '-----step6：超级用户删除表; expect:成功-----'
        self.log.info(text)
        sql_cmd = f"drop table {self.u_name}.{self.t_name};"
        msg = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(msg)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, msg, '执行失败:' + text)

        text = '-----step7：independent用户执行gs_restore语句; expect:成功-----'
        self.log.info(text)
        dump_cmd = f'source {macro.DB_ENV_PATH};' \
            f'gs_restore -U  {self.u_name} -W {macro.COMMON_PASSWD} ' \
            f'-p {self.pri_node.db_port} -d {self.pri_node.db_name} ' \
            f'{self.dump_path} -n {self.u_name} -t {self.t_name} '
        msg = self.common.get_sh_result(self.pri_node, dump_cmd)
        self.assertIn('restore operation successful', msg, '执行失败:' + text)

        text = '-----step8：切换independent用户,查询表; expect:成功-----'
        self.log.info(text)
        sql_cmd = f"select * from {self.u_name}.{self.t_name};"
        msg = self.pri_sh.execut_db_sql(sql_cmd, sql_type=connect)
        self.log.info(msg)
        self.assertIn('2 rows', msg, '执行失败:' + text)

    def tearDown(self):
        self.log.info('-----step9：清理环境-----')
        text1 = '-----删除用户 expect:成功-----'
        self.log.info(text1)
        drop_cmd = f"drop user if exists {self.u_name}," \
            f"{self.u_name_01} cascade;"
        drop_msg = self.pri_sh.execut_db_sql(drop_cmd)
        self.log.info(drop_msg)

        text2 = '-----修改参数enableSeparationOfDuty为初始值 expect:成功-----'
        self.log.info(text2)
        mod_msg1 = self.pri_sh.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'enableSeparationOfDuty='
                                             f'{self.default_value1}')
        restart_res = self.pri_sh.restart_db_cluster()

        text3 = '-----删除dump输出文件 expect:成功-----'
        self.log.info(text3)
        del_cmd = f'rm -rf {self.dump_path}'
        self.common.get_sh_result(self.pri_root, del_cmd)
        check_cmd = f'if [ -r {self.dump_path} ]; ' \
            f'then echo "exists"; else echo "not exists"; fi'
        del_msg = self.common.get_sh_result(self.pri_root, check_cmd)

        self.log.info('-----断言tearDown执行成功-----')
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, drop_msg,
                      '执行失败:' + text1)
        self.assertTrue(mod_msg1, '执行失败:' + text2)
        self.assertTrue(restart_res, '执行失败:' + text2)
        self.assertEqual('not exists', del_msg, '执行失败:' + text3)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
